#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <string.h>

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

int main()
{
    int pipefd[2];
    int ret = pipe(pipefd);
    if (ret == 1) // 创建匿名管道文件失败
    {
        ERR_EXIT("pipe :");
    }
    // 创建匿名文件成功
    // 创建子进程
    int pid = fork();
    if (pid == 0)
    {
        // 子进程
        close(pipefd[0]);
        std::string message;
        int cnt = 5;
        while (cnt--)
        {
            // message = "child say# hello world";
        
            message = 'A';
            int num = write(pipefd[1], message.c_str(), message.size());
            sleep(1);
            if (num < 0)
            {
                ERR_EXIT("write :");
            }
        }
        close(pipefd[1]);
        exit(0);
    }

    // 父进程
    close(pipefd[1]);

    char message[1024];
    int num = read(pipefd[0], message, 1024);
    message[num] = 0;
    std::cout << "received :" << message << " num =" << num << std::endl;

    waitpid(pid, nullptr, 0);
    close(pipefd[0]);
    return 0;
}

// int main()
// {
//     int pipefd[2];
//     pipe(pipefd);
//     std::cout << pipefd[0] <<  std::endl << pipefd[1] << std::endl;
//     return 0;
// }